const express = require('express')
const passport = require('passport')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')

const User = require('../../models/User')
const Todo = require('../../models/Todo')
const {
  secretOrKey
} = require('../../config/key')

const router = express.Router()

/**
 * @router /api/user/register post
 * @description 用户注册，存储用户信息
 * @access private
 */
router.post('/register', (req, res) => {

  const userInfo = req.body

  User.findOne({
      email: userInfo.email
    })
    .then((user) => {
      if (user) { // 如果用户已经存在
        return res.status(400).json({
          msg: '用户已存在...'
        })
      }
      // 如果用户不存在，在用户列表中创建一个用户，在todo列表中添加用户email

      // 创建一个新用户
      const newUser = new User({
        email: userInfo.email,
        username: userInfo.username,
        password: userInfo.password,
        avatar: userInfo.avatar,
        gender: userInfo.gender,
        constellation: userInfo.constellation,
        profession: userInfo.profession
      })
      // 在todo中开辟一块空间
      const newTodo = new Todo({
        email: userInfo.email
      })
      // 将用户email保存在todo中
      newTodo.save()
        .then(email => {
          console.log(email)
        })
        .catch(err => {
          throw err
        })

      // 使用bcrypt对密码进行加密操作
      bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          // Store hash in your password DB.
          if (err) {
            throw err
          }

          // 给用户密码进行加密
          newUser.password = hash

          // 将新增用户添加到数据库中
          newUser.save()
            .then(user => {
              console.log(user)
              res.json(user)
            })
            .catch(err => {
              throw err
            })
        })
      })
    })
})

/**
 * @router /api/user/login  get
 * @description 返回请求的json数据
 * @access private
 */
router.get('/login', passport.authenticate('jwt', {
  session: false
}), (req, res) => {
  const user = req.user
  res.json({
    email: user.email,
    username: user.username,
    avatar: user.avatars,
    gender: user.gender,
    constellation: user.constellation,
    profession: user.profession
  })
})

/**
 * @router /api/user/login  post
 * @description 返回token passport jwt
 * @access public
 */
router.post('/login', (req, res) => {
  // 记录用户邮箱和密码
  const email = req.body.email
  const password = req.body.password

  // 通过用户邮箱，向数据库中查找用户的对应信息
  User.findOne({
      email
    })
    .then(user => {
      // 判断用户是否存在
      if (!user) {
        return res.status(400).json({
          msg: '用户不存在，请注册...'
        })
      }

      // 如果用户已经存在，验证密码是否正确
      bcrypt.compare(password, user.password)
        .then(isMatch => {
          if (isMatch) {
            const rules = {
              id: user.id,
              email: user.email,
              username: user.username,
              avatar: user.avatar,
              gender: user.gender,
              constellation: user.constellation,
              profession: user.profession
            }

            jwt.sign(rules, secretOrKey, {
              expiresIn: '24h' // 设置token过期时间位24小时
            }, (error, token) => {
              if (error) {
                throw error
              }
              return res.json({
                msg: 'success',
                todo_token: `Bearer ${token}`
              })
            })
          } else {
            return res.status(400).json({
              msg: '密码错误'
            })
          }
        })
    })
})

module.exports = router